﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Transactions;

using MINERP.DAL;
using MINERP.BLL.PrintManage;
using MINERP.ComControls;
using MINERP.MODEL.PrintManage;
using MINERP.COM;
namespace MINERP.PrintManage
{
    public partial class FrmParperManager :Form
    {
        PaperInfoEntity _paperInfoEntity = null;
        PaperInfoBLL _bll = new PaperInfoBLL();
        MINERP.BLL.PrintManage.PrinterBLL printerBLL = new MINERP.BLL.PrintManage.PrinterBLL();
        BLLMain _bllMain = new BLLMain();
        private static FrmParperManager instance = null;
        public  double ChangePaperTitle = 0;
        public  bool isChange = false;
        public  double kaZhiLength = 0;
        public  string remark = string.Empty;
        public delegate void PostMsg();
        public event PostMsg Post;
        public int PrinterId;
        private FrmParperManager()
        {
            InitializeComponent();
        }
        public static FrmParperManager GetInstance
        {
            get
            {
                if (instance == null)
                {
                    instance = new FrmParperManager();
                }
                return instance;
            }
        }
        private void FrmParperManager_Load(object sender, EventArgs e)
        {
            LinkcmbPaperFace();
            LinkcmbPaperType();
            LinkGridControl(PrinterId);

        }

        private void btnAddPaper_Click(object sender, EventArgs e)
        {
            if (btnAdd.Text != "保存")
            {
                PrepareAdd(true);
                cmbPaperFace.Focus();
                return;
            }
            if (CheckData())
            {

                PaperInfo obj = new PaperInfo();
                obj.AddTime         = DateTime.Now;
                obj.LastLength      =Convert.ToDouble(txtLastLength.Text)*100;
                obj.LastPrintTime   = DateTime.Now;
                obj.Length          = Convert.ToDouble(txtLengh.Text)*100;
                obj.Width           = Convert.ToDouble(txtWidth.Text);
                obj.Operator        = FrmMain.loginName;
                obj.EndPaperLength  = Convert.ToDouble(txtPaperTitle.Text);
                obj.PaperConsumptionLength = (double)obj.EndPaperLength;
                obj.PaperEndArea = (double)obj.EndPaperLength * (double)obj.Width / 10000;
                obj.Remark          = txtRemark.Text;
                obj.Status          = 0;
                obj.PaperBreakArea = 0;
                obj.PaperTitleArea = 0;
                obj.LastBordId = 0;

                _bll.Add(obj, cmbPaperFace.Text, cmbPaperType.Text, PrinterId);
                //link datagrid
                LinkGridControl(PrinterId);

                PrepareAdd(false);
                MessageBox.Show("添加成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// 绑定GridControl
        /// </summary>
        private void LinkGridControl(int printerId)
        {
            List<PaperInfoEntity> list = new List<PaperInfoEntity>();

            try
            {
                foreach (var item in _bll.GetPaperInfoList(printerId))
                {
                    PaperInfoEntity paperInfoEntity = new PaperInfoEntity();

                    paperInfoEntity.PrintPaperId = item.PrintPaperId;
                    paperInfoEntity.AddTime = (DateTime)item.AddTime;
                    paperInfoEntity.LastLength = (float)item.LastLength;
                    paperInfoEntity.LastPrintTime = (DateTime)item.LastPrintTime;
                    paperInfoEntity.Length = (float)item.Length;
                    paperInfoEntity.Width = (float)item.Width;
                    paperInfoEntity.Operator = item.Operator;
                    paperInfoEntity.PaperTitle = (float)item.EndPaperLength;
                    if (item.Remark != null)
                    {
                        paperInfoEntity.Remark = item.Remark;
                    }
                    else
                    {
                        paperInfoEntity.Remark = string.Empty;
                    }
                    paperInfoEntity.Status = (int)item.Status;
                    if ((int)item.Status == 1)
                    {
                        paperInfoEntity.StatusName = "启用";
                    }
                    else
                    {
                        paperInfoEntity.StatusName = "停用";
                    }
                    paperInfoEntity.PaperFaceName = item.paperFace.Name;
                    paperInfoEntity.PaperTypeName = item.paperType.Name;
                    list.Add(paperInfoEntity);

                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            gridControlPaperInfo.DataSource = list;
            gridViewPaperInfo.RefreshData();
        }
        /// <summary>
        /// 绑定纸面
        /// </summary>
        private void LinkcmbPaperFace()
        {
            List<paperFace> list = _bllMain.GetPaperFaceList();
            foreach (paperFace obj in list)
            {
                if (obj.Name != "任意")
                {
                    cmbPaperFace.Properties.Items.Add(obj.Name);
                }
            }
        }
        /// <summary>
        /// 绑定纸型
        /// </summary>
        private void LinkcmbPaperType()
        {
            List<paperType> list = _bllMain.GetPaperTypeList();
            foreach (paperType obj in list)
            {
                if (obj.Name != "任意")
                {
                    cmbPaperType.Properties.Items.Add(obj.Name);
                }
            }

        }

        /// <summary>
        /// 检查数据完整性
        /// </summary>
        /// <returns></returns>
        private bool CheckData()
        {
            bool flag = true;
            if (cmbPaperFace.Text == string.Empty)
            {
                cmbPaperFace.Focus();
                MessageBox.Show("纸面不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbPaperType.Text == string.Empty)
            {
                cmbPaperType.Focus();
                MessageBox.Show("纸型不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (txtLengh.Text == string.Empty)
            {
                txtLengh.Focus();
                MessageBox.Show("初始长度不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (txtPaperTitle.Text == string.Empty)
            {
                txtPaperTitle.Focus();
                MessageBox.Show("纸头不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (txtWidth.Text == string.Empty)
            {
                txtWidth.Focus();
                MessageBox.Show("纸宽不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (txtLastLength.Text == string.Empty)
            {
                txtLastLength.Focus();
                MessageBox.Show("剩余长度不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            return flag;
        }

        /// <summary>
        /// 添加前控件设置

        /// </summary>
        /// <param name="bl"></param>
        private void PrepareAdd(bool bl)
        {
            cmbPaperFace.Enabled = bl;
            cmbPaperType.Enabled = bl;
            txtLengh.Enabled = bl;
            txtPaperTitle.Enabled = bl;
            txtLastLength.Enabled = bl;
            txtRemark.Enabled = bl;
            txtWidth.Enabled = bl;

            cmbPaperFace.Text = string.Empty;
            cmbPaperType.Text = string.Empty;
            txtLengh.Text = string.Empty;
            txtPaperTitle.Text = string.Empty;
            txtLastLength.Text = string.Empty;
            txtRemark.Text = string.Empty;
            txtWidth.Text = string.Empty;

            if (bl)
            {

                btnAdd.Text = "保存";
                btnUpdate.Enabled = false;
            }
            else
            {
                btnAdd.Text = "添加";
                btnUpdate.Enabled = true;
            }
        }

        /// <summary>
        /// 更新前控件设置

        /// </summary>
        /// <param name="bl"></param>
        //private void PrepareUpdate(bool bl)
        //{

        //    cmbPaperFace.Enabled = bl;
        //    cmbPaperType.Enabled = bl;
        //    txtLengh.Enabled = bl;
        //    txtPaperTitle.Enabled = bl;
        //    txtLastLength.Enabled = bl;
        //    txtRemark.Enabled = bl;

        //    if (bl)
        //    {

        //        btnUpdate.Text = "保存";
        //        btnAdd.Enabled = false;

        //    }
        //    else
        //    {
        //        btnUpdate.Text = "更新";
        //        btnAdd.Enabled = true;
        //    }
        //}
        private void FrmParperManager_FormClosing(object sender, FormClosingEventArgs e)
        {
            instance = null;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            cmbPaperFace.Enabled = false;
            cmbPaperType.Enabled = false;
            txtLengh.Enabled = false;
            txtPaperTitle.Enabled = false;
            txtLastLength.Enabled = false;
            txtRemark.Enabled = false;

            btnAdd.Text = "添加";
            btnAdd.Enabled = true;
            btnUpdate.Enabled = true;
        }
        //换纸
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (_paperInfoEntity != null)
            {
                PaperInfo paperInfo = _bll.GetPaperInfoObj(_paperInfoEntity.PrintPaperId);
                if (paperInfo.Status != (int)PaperInfoStatus.Using)
                {
                    if (paperInfo.LastLength > 10)
                    {
                        FrmPaperTitleInput frmPaperTiTleInput = new FrmPaperTitleInput();
                        frmPaperTiTleInput.ShowDialog(this);
                        if (isChange)
                        {
                            //using (TransactionScope ts = new TransactionScope())
                            //{
                                try
                                {
                                    paperInfo=_bll.UpdatePaper(ChangePaperTitle, paperInfo, FrmMain.loginName,PrinterId);
                                    //ts.Complete();

                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }
                            //}
                            ((FrmMain)this.Owner).PreRemainLength = Math.Round((double)paperInfo.LastLength, 2);
                            ((FrmMain)this.Owner)._paperInfo = paperInfo;
                            isChange = false;
                            LinkGridControl(PrinterId);
                            Post();
                            ChangePaperTitle = 0;
                            MessageBox.Show("换纸成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        MessageBox.Show("该打印纸长度不够！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show("该打印纸正在使用中！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("没有选择纸！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
               
            }
            
        }

        //添加卡纸记录
        private void btnAddKaZhi_Click(object sender, EventArgs e)
        {
            if (_paperInfoEntity != null)
            {

                FrmKaZhi frmKaZhi = new FrmKaZhi();
                frmKaZhi.ShowDialog(this);
                if (isChange)
                {
                    using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
                    {
                        double totalKazhiLength = 0;
                        PaperInfo paperInfo =entities.PaperInfo.FirstOrDefault(p=>p.PrintPaperId==_paperInfoEntity.PrintPaperId);
                        if (paperInfo != null)
                        {
                            using (TransactionScope ts = new TransactionScope())
                            {
                                paperInfo.LastLength -= kaZhiLength;
                                paperInfo.PaperConsumptionLength += kaZhiLength;
                                MINERP.DAL.PaperWasteRecord paperWasteRecord = new MINERP.DAL.PaperWasteRecord();
                                paperWasteRecord.OperationType = (int)WastePaperOperationType.kazhi;
                                paperWasteRecord.OperationTime = DateTime.Now;
                                paperWasteRecord.Operator = FrmMain.loginName;
                                paperWasteRecord.PaperInfo = paperInfo;
                                paperWasteRecord.PaperWasteLength = kaZhiLength;
                                paperWasteRecord.PaperWasteWidth = paperInfo.Width;
                                paperWasteRecord.ReMark = remark;

                                try
                                {
                                    entities.SaveChanges();
                                    ts.Complete();
                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }
                            }
                        }
                        if (!paperInfo.PaperWasteRecord.IsLoaded)
                        {
                            paperInfo.PaperWasteRecord.Load();
                        }
                        foreach (var item in paperInfo.PaperWasteRecord)
                        {
                            if (item.OperationType == (int)WastePaperOperationType.kazhi)
                            {
                                totalKazhiLength +=(double) item.PaperWasteLength;
                            }
                        }
                        paperInfo.PaperBreakArea = (double)totalKazhiLength * (double)paperInfo.Width / 10000;
                        entities.SaveChanges();
                    }
                    isChange = false;
                    kaZhiLength = 0;
                    LinkGridControl(PrinterId);
                    Post();
                    MessageBox.Show("添加卡纸记录成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
            }
            else
            {
                MessageBox.Show("没有选择纸！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void gridViewPaperInfo_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            _paperInfoEntity = (PaperInfoEntity)gridViewPaperInfo.GetFocusedRow();
        }

        private void txtLengh_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                Convert.ToDouble(txtLengh.Text.Trim());
            }
            catch
            {
                MessageBox.Show("请输入数字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtLengh.Text = string.Empty;
            }
        }

        private void txtPaperTitle_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                Convert.ToDouble(txtPaperTitle.Text.Trim());
                txtLastLength.Text = Math.Round(((Convert.ToDouble(txtLengh.Text)*100 - Convert.ToDouble(txtPaperTitle.Text))/100),2).ToString();
            }
            catch
            {
                MessageBox.Show("请输入数字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtPaperTitle.Text = string.Empty;
            }
        }

        private void txtLastLength_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                Convert.ToDouble(txtLastLength.Text.Trim());
            }
            catch
            {
                MessageBox.Show("请输入数字", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtLastLength.Text = string.Empty;
            }
        }
        //设置特殊行的颜色
        private void gridViewPaperInfo_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                PaperInfoEntity paperInfoEntity = (PaperInfoEntity)gridViewPaperInfo.GetRow(e.RowHandle);
                if (paperInfoEntity.Status == 1)
                {
                    e.Appearance.ForeColor = Color.ForestGreen;
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {

            PaperInfo pi = _bll.GetPaperInfoObj(_paperInfoEntity.PrintPaperId);
            if (!(pi.Status == (int)PaperInfoStatus.Using))
            {

                if (DialogResult.OK == MessageBox.Show("确定删除吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    _bll.Delete(_paperInfoEntity.PrintPaperId);
                    LinkGridControl(PrinterId);
                }
            }
            else
            {
                MessageBox.Show("正在使用的纸不能删除！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
        }

        private void gridViewPaperInfo_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (MouseButtons.Right == e.Button)
            {
                PaperInfoEntity paperInfo = (PaperInfoEntity)gridViewPaperInfo.GetFocusedRow();
                //if (paperInfo.Status != 1)
                //{
                    FrmAddPaperLength frmAddPaperlength = new FrmAddPaperLength();
                    frmAddPaperlength.linkGridView = new FrmAddPaperLength.LinkGridView(LinkGridControl);
                    frmAddPaperlength.PaperId = paperInfo.PrintPaperId;
                    frmAddPaperlength.PrinterId = PrinterId;
                    frmAddPaperlength.ShowDialog((FrmMain)this.Owner);
                //}
            }
        }

        private void btnCalibration_Click(object sender, EventArgs e)
        {
            FrmCalibration frmCalibration = new FrmCalibration(_paperInfoEntity.PrintPaperId);
            frmCalibration.ShowDialog();
        }


    }
}
